<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Wechat;
use app\common\model\activity\Activity;
use app\common\model\activity\Sign as ActivitySign;
use app\common\model\Banner;
use app\common\model\essay\Category;
use app\common\model\essay\Essay;
use app\common\model\events\Category as EventsCategory;
use app\common\model\events\Events;
use app\common\model\events\Order;
use app\common\model\events\Sign;
use app\common\model\serve\Order as ServeOrder;
use app\common\model\serve\Serve;
use app\common\model\User;
use think\Db;
use think\Validate;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['index', 'events', 'activity', 'category', 'essay', 'essay_info', 'division', 'players', 'players_info', 'serve_list', 'serve_info'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {

        $banner = Banner::all();
        $activity_zone =  config('site.activity_zone') ? cdnurl(config('site.activity_zone'), true) : '';
        $event_area = config('site.event_area') ? cdnurl(config('site.event_area'), true) : '';
        $this->success('请求成功', compact('banner', 'activity_zone', 'event_area'));
    }

    /**
     * @Author LK
     * @ApiTitle (赛事)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function events()
    {
        $infos = Events::paginate();
        $uid = $this->auth->id;
        foreach ($infos as $key => $v) {
            $v->is_sign = Sign::get(['user_id' => $uid, 'e_id' => $v->id, 'state' => ['in', ['0', '10']]]) ? true : false;
        }
        $this->success('请求成功', $infos);
    }
    /**
     * @Author LK
     * @date: 2024-01-27 
     * @ApiTitle (赛事详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function events_info()
    {
        $param =  request()->param();
        extract($param);
        $uid = $this->auth->id;
        $infos = Events::get($id);
        $infos->is_sign = Sign::get(['user_id' => $uid, 'e_id' => $id, 'state' => ['in', ['0', '10']]]) ? true : false;
        $this->success('请求成功', $infos);
    }
    /**
     * @Author LK
     * @ApiTitle (活动)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function activity()
    {
        $infos = Activity::paginate();
        $uid = $this->auth->id;
        foreach ($infos as $key => $v) {
            $v->is_sign = ActivitySign::get(['a_id' => $v['id'], 'user_id' => $uid]) ? true : false;
        }
        $this->success('请求成功', $infos);
    }
    /**
     * @Author LK
     * @date: 2024-01-27 
     * @ApiTitle (活动详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function activity_info()
    {
        $param =  request()->param();
        extract($param);
        $uid = $this->auth->id;
        $infos = Activity::get($id);
        $infos->is_sign = ActivitySign::get(['a_id' => $id, 'user_id' => $uid]) ? true : false;
        $this->success('请求成功', $infos);
    }
    /**
     * @Author LK
     * @ApiTitle (活动报名)
     * @ApiMethod (post)
     * @ApiParams (name="a_id", type="integer", required=true, sample="", description="活动ID")
     * @ApiParams (name="enterprise", type="string", required=true, sample="", description="企业名称")
     * @ApiParams (name="type", type="string", required=true, sample="", description="企业类型:1=工厂,2=门店")
     * @ApiParams (name="name", type="string", required=true, sample="", description="联系人")
     * @ApiParams (name="gender", type="string", required=true, sample="", description="性别:male=男,female=女")
     * @ApiParams (name="mobile", type="string", required=true, sample="", description="手机号")
     * @ApiParams (name="city", type="string", required=true, sample="", description="地区")
     * @ApiParams (name="description", type="string", required=true, sample="", description="备注")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function activity_sign()
    {
        $param = request()->param();
        extract($param);
        $uid = $this->auth->id;
        $sign = ActivitySign::get(['user_id' => $uid, 'a_id' => $a_id]);
        if ($sign) {
            $this->error('已报名');
        }
        try {
            $data = [
                'enterprise' => $enterprise,
                'type' => $type,
                'name' => $name,
                'mobile' => $mobile,
                'city' => $city,
                'description' => $description,
                'a_id' => $a_id,
                'user_id' => $uid,
            ];
            ActivitySign::create($data);
        } catch (\Exception $e) {
            $this->error('报名失败：' . $e->getMessage());
        }
        $this->success('报名成功');
    }
    /**
     * @Author LK
     * @date: 2024-02-04 
     * @ApiTitle (我的活动)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="type", type="string", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function my_activity()
    {
        $uid = $this->auth->id;
        $aids = ActivitySign::where('user_id', $uid)->column('a_id');
        $lists = Activity::whereIn('id', $aids)->paginate();
        $this->success('请求成功', $lists);
    }

    /**
     * @Author LK
     * @ApiTitle (资讯分类)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function category()
    {
        $lists = Category::all();
        $this->success('请求成功', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (资讯)
     * @ApiMethod (get)
     * @ApiParams (name="category_id", type="integer", required=true, sample="0=全部", description="分类ID:0=全部")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function essay()
    {
        $params = request()->param();
        extract($params);
        $model = new Essay();
        if ($category_id > 0) {
            $model->where('category_id', $category_id);
        }
        $lists = $model->order('id desc')->paginate();

        $this->success('请求成功', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (资讯详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function essay_info()
    {
        $params = request()->param();
        extract($params);
        $info = Essay::get($id);
        $this->success('请求成功', $info);
    }

    /**
     * @Author LK
     * @ApiTitle (赛事报名)
     * @ApiMethod (POST)
     * @ApiParams (name="c_id", type="integer", required=true, sample="", description="赛区ID")
     * @ApiParams (name="e_id", type="integer", required=true, sample="", description="赛事ID")
     * @ApiParams (name="title", type="integer", required=true, sample="", description="名称")
     * @ApiParams (name="gender", type="string", required=true, sample="", description="性别:male=男,female=女")
     * @ApiParams (name="mobile", type="string", required=true, sample="", description="手机号")
     * @ApiParams (name="hobbies", type="string", required=true, sample="", description="兴趣爱好")
     * @ApiParams (name="innovation", type="string", required=true, sample="", description="创业创新")
     * @ApiParams (name="images", type="string", required=true, sample="", description="生活照")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function events_sign()
    {
        $params = request()->param();
        extract($params);
        $uid = $this->auth->id;
        $rule = [
            'c_id'   => 'require',
            'e_id'  => 'require',
            'title' => 'require',
            'gender' => 'require',
            'mobile' => 'require',
            'images' => 'require',
        ];
        $msg = [
            'e_id.require'  => '参数错误',
            'c_id.require'  => '请选择赛区',
            'title.require'  => '请输入姓名',
            'gender.require'  => '请选择性别',
            'mobile.require'  => '请输入联系方式',
            'images.require'  => '请上传生活照',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($params);
        if (!$result) {
            $this->error(__($validate->getError()));
        }
        $events = Events::get($e_id);
        if (!$events) {
            $this->error('赛事不存在');
        }
        $time = explode(' - ', $events->workrange);
        if (time() < strtotime($time[0]) || time() > strtotime($time[1])) {
            $this->error('不在报名时间');
        }
        $category = EventsCategory::get($c_id);
        if (!$category) {
            $this->error('赛区不存在');
        }
        $sign = Sign::get(['user_id' => $uid, 'e_id' => $e_id, 'state' => ['in', ['0', '10']]]);
        if ($sign) {
            $this->error('已报名赛事');
        }
        $params['events_info'] = json_encode($events);
        $params['user_id'] = $uid;
        $params['category_name'] = $category->title;
        $res = Sign::create($params, true);
        if ($res) {
            $this->success('报名成功');
        }
        $this->error('报名失败');
    }
    /**
     * @Author LK
     * @ApiTitle (赛区)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="赛事ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function division()
    {
        $params = request()->param();
        extract($params);
        $list = EventsCategory::all(['e_id' => $id]);
        $this->success('', $list);
    }
    /**
     * @Author LK
     * @ApiTitle (参数选手)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="赛区ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function players()
    {
        $params = request()->param();
        extract($params);
        $list = Sign::where(['c_id' => $id, 'state' => '10'])->paginate();
        $this->success('', $list);
    }
    /**
     * @Author LK
     * @ApiTitle (选手详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="选手ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function players_info()
    {
        $params = request()->param();
        extract($params);
        $list = Sign::get($id, ['events']);
        $free_times = Order::where('status', '1')->where('user_id', $this->auth->id)->where('sign_id', $id)->where('type', 1)->count();
        $list['free_times'] = bcsub(3, $free_times, 0);
        $this->success('', $list);
    }
    /**
     * @Author LK
     * @ApiTitle (投票)
     * @ApiMethod (post)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function vote()
    {
        $params = request()->param();
        extract($params);
        $uid = $this->auth->id;
        $sign = Sign::get($id);
        if (!$sign) {
            $this->error('选手信息不存在');
        }
        $events = Events::get($sign->e_id);
        $num = Order::where('status', '1')->where('user_id', $this->auth->id)->where('sign_id', $id)->where('type', 1)->count();
        $data = [
            'user_id' => $uid,
            'sn' => sn('events_order', 'sn', 'TP'),
            'price' => $num < 3 ? 0 : $events->price,
            'type' =>  $num < 3 ? '1' : '2',
            'status' => $num < 3 ? '1' : '0',
            'sign_info' => json_encode($sign),
            'sign_name' => $sign->title,
            'sign_id' => $sign->id,
            'e_id' => $sign->e_id,
        ];
        Db::startTrans();
        try {
            $res = Order::create($data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('', $res->id, $num < 3 ? 1 : 200);
    }

    /**
     * @Author LK
     * @ApiTitle (服务大厅)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function serve_list()
    {
        $lists = Serve::paginate();
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (服务详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function serve_info()
    {
        $params = request()->param();
        extract($params);
        $lists = Serve::get($id);
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (服务购买)
     * @ApiMethod (POST)
     * @ApiParams (name="name", type="string", required=true, sample="", description="联系人")
     * @ApiParams (name="mobile", type="string", required=true, sample="", description="手机号")
     * @ApiParams (name="pid", type="string", required=true, sample="", description=推荐人")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function serve_pay()
    {
        $params = request()->param();
        extract($params);
        $uid = $this->auth->id;
        $serve = Serve::get($id);
        if (!$serve) {
            $this->error('服务不存在');
        }
        Db::startTrans();
        try {
            if (isset($pid) && $pid > 0) {
                $user = User::get($uid);
                if (isset($user) && !$user->pid) {
                    $user->pid = $pid;
                    $user->save();
                }
            }
            $data = [
                'name' => $name,
                'mobile' => $mobile,
                'serve_info' => json_encode($serve),
                'serve_id' => $id,
                'user_id' => $uid,
            ];
            ServeOrder::create($data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('失败:' . $e->getMessage());
        }
        $this->success('成功');
    }
    /**
     * @Author LK
     * @ApiTitle (我的赛事)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="type", type="string", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function my_events()
    {
        $data = Sign::where(['user_id' => $this->auth->id])->order('id desc')->paginate();
        $this->success('', $data);
    }
    /**
     * @Author LK
     * @ApiTitle (我的投票)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="type", type="string", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */

    public function my_vote()
    {
        $sign_ids = Order::where(['user_id' => $this->auth->id, 'status' => '1'])->column('sign_id');
        $lists = Sign::where(['state' => 10])->whereIn('id', $sign_ids)->group('user_id')->select();
        $this->success('', $lists);
    }


    /**
     * @Author LK
     * @ApiTitle (我的投票订单)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="type", type="string", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */

    public function my_vote_order()
    {
        $lists = Order::where(['user_id' => $this->auth->id, 'status' => '1', 'type' => '2'])->paginate();
        $this->success('', $lists);
    }

    /**
     * @Author LK
     * @ApiTitle (我的推广)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function my_team()
    {
        $lists = User::where('pid', $this->auth->id)->paginate();
        $this->success('', $lists);
    }
}
